/*
 Name:		Sketch1vs.ino
 Created:	2016/8/16 15:06:50
 Author:	mgr9525
*/

#define PT_USE_TIMER
#define PT_USE_SEM

#include "pThread\pt.h"
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>

ruisth thread1, thread2;

// the setup function runs once when you press reset or power the board
void setup() {
	Serial.begin(9600);

	/*Mirf.spi = &MirfHardwareSpi;
	Mirf.init();
	
	Mirf.setRADDR((byte *)"serv1"); // 本地名
	Mirf.payload = 23; // 长度
	Mirf.channel = 4; // 信道

	Mirf.config();*/

	TH_INIT(&thread1);
	TH_INIT(&thread2);

	Serial.println("setup ok!");

	pinMode(13, OUTPUT);
}

int thread1_entry(ruispt *pt);
int thread2_entry(ruispt *pt);

// the loop function runs over and over again until power down or reset
void loop() {
	thread1_entry(&thread1);
	thread2_entry(&thread2);
}

int thread1_entry(ruisth *th){
	PT_BEGIN(&th->pt);

	Serial.println("thread1_entry setuping!");

	while (1) {
		/* Wait until the other protothread has set its flag. */
		PT_SEM_WAIT(&th->pt, &th->sem);

		/* And we loop. */
		digitalWrite(13, HIGH);
		PT_TIMER_DELAY(&th->pt, 500);
		digitalWrite(13, LOW);
		PT_TIMER_DELAY(&th->pt, 500);

		PT_SEM_SIGNAL(&th->pt, &th->sem);
	}
	//PT_WAIT_UNTIL();
	PT_END(&th->pt);
}

int thread2_entry(ruisth *th){
	PT_BEGIN(&th->pt);

	Serial.println("thread2_entry setuping!");

	while (1) {
		/* Let the other protothread run. */
		PT_SEM_WAIT(&th->pt, &th->sem);

		/* And we loop. */
		Serial.println("hey!");
		PT_TIMER_DELAY(&th->pt, 1000);

		PT_SEM_SIGNAL(&th->pt, &th->sem);
		PT_YIELD(&th->pt); //Check the other events.
	}
	//PT_WAIT_UNTIL();
	PT_END(&th->pt);
}